/**
 * @file ProductDetailPage.jsx
 * @description 商品详情页面组件。
 */
import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux'; // 引入 useSelector
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css';
import Marquee from "react-fast-marquee";
import { addItem } from '../store/cartSlice';
import { addItemToWishlist, removeItemFromWishlist } from '../store/wishlistSlice'; // 导入心愿单 actions
import toast from 'react-hot-toast';
import { fetchProductById, fetchProductsByCategory } from '../services/api';
import { FaStar, FaCartPlus, FaHeart, FaRegHeart } from 'react-icons/fa'; // 导入心形图标

const ProductDetailPage = () => {
  const { id } = useParams();
  const [product, setProduct] = useState(null);
  const [similarProducts, setSimilarProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadingSimilar, setLoadingSimilar] = useState(true);
  const dispatch = useDispatch();
  const wishlistItems = useSelector((state) => state.wishlist.items); // 获取心愿单列表
  const { isAuthenticated } = useSelector((state) => state.auth); // 获取登录状态，用于判断是否显示心愿单按钮

  useEffect(() => {
    if (!id) {
      setLoading(false);
      setLoadingSimilar(false);
      setProduct(null);
      setSimilarProducts([]);
      return;
    }

    const getProductDetails = async () => {
      setLoading(true);
      setLoadingSimilar(true);
      setProduct(null);
      setSimilarProducts([]);

      try {
        const productData = await fetchProductById(id);

        if (productData && productData.id) {
          setProduct(productData);

          if (productData.category) {
            const similarData = await fetchProductsByCategory(productData.category);
            if (similarData) {
              setSimilarProducts(similarData.filter(p => p.id !== productData.id).slice(0, 6));
            }
          }
        } else {
          toast.error("无法加载商品详情！");
        }
      } catch (error) {
        toast.error("获取商品详情时发生错误！");
      } finally {
        setLoading(false);
        setLoadingSimilar(false);
      }
    };

    getProductDetails();
  }, [id]);

  const handleAddItemToCart = (item) => {
    if (item && item.id) {
      dispatch(addItem(item));
      toast.success(`${item.title ? item.title.substring(0,20) : '商品'}... 已添加到购物车!`);
    } else {
      toast.error("无法添加此商品到购物车。");
    }
  };

  const handleToggleWishlist = (item) => {
    if (!item || !item.id) {
      toast.error("操作心愿单商品失败。");
      return;
    }
    if (!isAuthenticated) { // 检查用户是否登录
        toast.error("请先登录再操作心愿单！");
        // 可以选择导航到登录页: navigate('/login', { state: { from: location } });
        return;
    }
    const isInWishlist = wishlistItems.some(wishlistItem => wishlistItem.id === item.id);
    if (isInWishlist) {
      dispatch(removeItemFromWishlist(item.id));
    } else {
      dispatch(addItemToWishlist(item));
    }
  };


  const LoadingProduct = () => (
    <>
      <div className="col-md-6">
        <Skeleton height={400} />
      </div>
      <div className="col-md-6" style={{ lineHeight: 2 }}>
        <Skeleton height={30} width={300} className="mb-3" />
        <Skeleton count={3} />
        <Skeleton height={30} width={150} className="mt-3 mb-3" />
        <Skeleton height={50} className="mb-3"/>
        <Skeleton count={4} />
        <div className="mt-4">
            <Skeleton height={50} width={180} inline={true} style={{ marginRight: 10 }} />
            <Skeleton height={50} width={120} inline={true} />
        </div>
      </div>
    </>
  );

  const ShowProduct = () => {
    if (!product) return null;
    const isInWishlist = wishlistItems.some(item => item.id === product.id);

    return (
      <>
        <div className="col-md-6 text-center position-relative"> {/* 添加 position-relative */}
          <img 
            src={product.image} 
            alt={product.title} 
            className="img-fluid"
            style={{ maxHeight: '400px', maxWidth: '100%', objectFit: 'contain' }} 
          />
           {isAuthenticated && ( /* 仅在登录后显示心愿单按钮 */
                <button 
                    className="btn btn-lg position-absolute top-0 end-0 m-2" // 增大按钮，调整位置
                    onClick={() => handleToggleWishlist(product)}
                    aria-label={isInWishlist ? "从心愿单移除" : "添加到心愿单"}
                    style={{ backgroundColor: 'rgba(255,255,255,0.7)', borderRadius: '50%', zIndex: 10, padding: '0.5rem 0.7rem' }}
                >
                    {isInWishlist ? <FaHeart className="text-danger fs-4" /> : <FaRegHeart className="text-danger fs-4"/>}
                </button>
            )}
        </div>
        <div className="col-md-6">
          <h4 className="text-uppercase text-black-50">{product.category}</h4>
          <h1 className="display-5">{product.title}</h1>
          <p className="lead fw-bolder">
            评分 {product.rating && product.rating.rate}
            <FaStar className="ms-1" style={{color: "gold"}} />
          </p>
          <h3 className="display-6 fw-bold my-4">$ {product.price}</h3>
          <p className="lead">{product.description}</p>
          <button className="btn btn-outline-dark px-4 py-2" onClick={() => handleAddItemToCart(product)}>
            <FaCartPlus className="me-1" />
            添加到购物车
          </button>
          <Link to="/cart" className="btn btn-dark ms-2 px-3 py-2">
            去购物车
          </Link>
        </div>
      </>
    );
  };

  const LoadingSimilarProducts = () => (
    <div className="d-flex">
      {[...Array(4)].map((_, index) => (
        <div className="mx-2" key={index} style={{ width: 'calc(25% - 1rem)'}}>
          <Skeleton height={200} />
          <Skeleton height={20} className="mt-2"/>
          <Skeleton height={30} width="60%" className="mt-1"/>
        </div>
      ))}
    </div>
  );

  const ShowSimilarProducts = () => (
    <Marquee pauseOnHover={true} gradient={false} speed={50}>
      {similarProducts.map((item) => {
        const isInWishlist = wishlistItems.some(wishlistItem => wishlistItem.id === item.id);
        return (
          <div key={item.id} className="card mx-2 text-center" style={{ minWidth: '250px', maxWidth: '250px', flex: '0 0 auto' }}>
             <div className="position-relative">
                <Link to={`/product/${item.id}`} className="text-decoration-none text-dark d-block">
                    <img
                    src={item.image}
                    className="card-img-top p-3"
                    alt={item.title}
                    style={{ height: '200px', objectFit: 'contain' }}
                    />
                </Link>
                {isAuthenticated && (
                    <button 
                        className="btn btn-sm position-absolute top-0 end-0 m-2"
                        onClick={() => handleToggleWishlist(item)}
                        aria-label={isInWishlist ? "从心愿单移除" : "添加到心愿单"}
                        style={{ backgroundColor: 'rgba(255,255,255,0.7)', borderRadius: '50%', zIndex: 10 }}
                    >
                        {isInWishlist ? <FaHeart className="text-danger" /> : <FaRegHeart className="text-danger"/>}
                    </button>
                )}
            </div>
            <Link to={`/product/${item.id}`} className="text-decoration-none text-dark">
                <div className="card-body">
                <h5 className="card-title fs-6" style={{height: '3em', overflow: 'hidden'}}>
                    {item.title.substring(0, 40)}...
                </h5>
                <p className="card-text fw-bold mb-2">${item.price}</p>
                </div>
            </Link>
            <div className="card-footer bg-transparent border-top-0 pb-3">
              <button
                  className="btn btn-outline-dark btn-sm"
                  onClick={() => handleAddItemToCart(item)}
                >
                  <FaCartPlus className="me-1" />
                  添加到购物车
              </button>
            </div>
          </div>
        );
      })}
    </Marquee>
  );

  return (
    <div className="container my-5 py-5">
      <div className="row g-5">
        {loading ? <LoadingProduct /> : (product ? <ShowProduct /> : <div className="col-12 text-center"><p>无法加载商品详情。</p></div>)}
      </div>
      {product && (
        <div className="row my-5 pt-5">
          <div className="col-12">
            <h2 className="mb-4">您可能也喜欢</h2>
            {loadingSimilar ? <LoadingSimilarProducts /> : (similarProducts.length > 0 ? <ShowSimilarProducts /> : <p className="text-center">暂无相似商品。</p>)}
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductDetailPage;